package com.ag.zhh.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.ag.contactTree.TreeNode;

public class DeptIDUtil {

	public static String getNewDeptIDByFDId(String fDeptId, List deptChildren)
			throws Exception {
		List<String> fdeptIdStringList = splitStringByTwo(fDeptId);
		int layerCount = fdeptIdStringList.indexOf("00");
		if (layerCount == -1) {
			throw new Exception("DeptIDUtil：超出层数限制，不能增加子部门");
		}
		String headId = StringUtils.substring(fDeptId, 0, layerCount * 2);

		// 获取Id最大的子部门
		String maxNodeId = null;
		if (deptChildren == null || deptChildren.size() == 0) {
			//没有子部门
			maxNodeId = fDeptId;
		} else {
			for (Object o : deptChildren) {
				if (maxNodeId == null) {
					maxNodeId = ((TreeNode) o).getNodeId().substring(2);
				}
				if (maxNodeId.compareTo(((TreeNode) o).getNodeId().substring(2)) < 0) {
					maxNodeId = ((TreeNode) o).getNodeId().substring(2);
				}
			}
		}

		// System.out.println(maxIdNode);
		String code = StringUtils.substring(maxNodeId, layerCount * 2,
				layerCount * 2 + 2);
		int intcode = Integer.parseInt(code);
		intcode++;
		String stringcode = null;
		if (intcode < 10) {
			stringcode = "0" + intcode;
		} else {
			stringcode = (new Integer(intcode)).toString();
		}
		String originId = headId + stringcode;

		for (int i = layerCount; i < 4; i++) {
			originId += "00";
		}

		return originId;
	}

	public static List<String> splitStringByTwo(String str) {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i + 2 <= str.length(); i += 2) {
			list.add(StringUtils.substring(str, i, i + 2));
		}
		return list;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<String> list = splitStringByTwo("0102020000");
		System.out.println(ArrayUtils.toString(list.toArray()));
		System.out.println(list.indexOf("00"));
		System.out.println(StringUtils.substring("0102020000", 0, list
				.indexOf("00") * 2));
		System.out.println(StringUtils.substring("01020203000", list
				.indexOf("00") * 2, list.indexOf("00") * 2 + 2));
		String str = StringUtils.substring("0102020000", 0,
				list.indexOf("00") * 2);
		str += StringUtils.substring("0102020000", list.indexOf("00") * 2, list
				.indexOf("00") * 2 + 2);
		for (int i = list.indexOf("00"); i < 4; i++) {
			str += "00";
		}
		System.out.println("重新组合：" + str);
		System.out.println(Integer.parseInt("20"));
	}

}
